import BASE_URL from './url';
import {checkStatus,parseJSON,tojson} from './tools';
import {message} from 'antd';
/*
 * 基本请求request
 * */
function isHttpUrl(url){
    var reg=new RegExp("^http","i");
    return reg.test(url);
}





export async function request(url,options) {
    let requestUrl = url;
    let jwt = JSON.parse(localStorage.getItem("mspa_user") );

    console.log('sss',jwt);
    let result ;
    if (jwt=== null) {
    }
    else
    {
        result = jwt.Ticket
    }   


      if(!isHttpUrl(requestUrl)){
          requestUrl = BASE_URL+url;
      }
      return  baseRequest(requestUrl, {
          headers: {
              'Accept': 'application/json',
              'Content-Type': 'application/json',
              'X-Requested-With': 'XMLHttpRequest',
              'auth':result
          },
         credentials: 'include',
          ...options
      })
  }
  



  /* 第一层fetch，处理401状态码，alert错误 */
function baseRequest(url,options){
   let newUrl = ChangeOptions(url,options);
   //console.log(newUrl);
    //console.log(options);

    return fetch(newUrl, {
        ...options
    })
    .then(checkStatus)
    .then(parseJSON)
    .then(tojson)
    .catch(e=>{
        const res = e.response;
        console.log(res);
        if(res&&res.status===401){
            console.error('baseRequestWithCodeProcess401 捕捉到 401 错误');
            return new Promise((resolve,reject)=>{
                reject(e);
            })
        }
        else if(res && res.data &&res.data.status===200){
            if(!res.data.is_success)
            {
                message.error(
                    res.data.msg
                    ||'参数异常'
                );
            }

            return undefined;
            // return new Promise((resolve,reject)=>{
            //     reject(e);
            // })

        }
        else {
            // 对错误进行统一的错误提示，错误提示由后端提供
            if(e.response){
                return e.response.json().then(result=>{
                    message.error(
                        result&&result.error&&result.error.message
                        ||'服务器错误'
                    );
                    return new Promise((resolve,reject)=>{
                        reject(e);
                    })
                })
            } else {
                
                message.error(`服务器错误:${e}`);
                return new Promise((resolve,reject)=>{
                    reject(e);
                })
            }
        }
    })
}


function  ChangeOptions(url,options) {
    let {method,ReqParamers,body}   = options;
    let newUrl = url;
    if(method == null || method == undefined )
        method == "GET";
    if(ReqParamers !=null && method != undefined){
        //更改URL地址
        if(method.toUpperCase() == "GET"){
            newUrl= url +'?'+ window.$.param(ReqParamers);
        }
        else  if(method.toUpperCase() == "POST" && (body == null || body==undefined)){
            //添加BODY
            options['body'] =JSON.stringify(ReqParamers);
        }
    }
    return newUrl;
}